<script setup>
import { ref, onMounted, toRefs, watch, nextTick } from 'vue'
import Croppr from 'croppr';
import 'croppr/dist/croppr.css';
import { onDownCanvas } from '@/js/function.js';

const props = defineProps({
    url: String,
    option: {
        type: Object,
        default: {
            width: 500,
            height: 500
        }
    }
});
//需要响应式时使用toRefs
const { url, option } = toRefs(props);
//向父级传递消息
const emits = defineEmits(['tohost'])
function sindEmit(msg) {
    emits('tohost', msg);
}
var cropInstance;
watch(() => props.url, (newVal, oldValue) => {
    nextTick(() => {
        cropInstance.destroy()
        cropInstance = new Croppr('#croppr', {
            aspectRatio: 1,
            startSize:[100,100,'%'],
        });
    })
})

onMounted(() => {

    cropInstance = new Croppr('#croppr', {
        aspectRatio: 1,
        startSize:[100,100,'%'],
        onCropEnd: function (data) {
            console.log(data.x, data.y, data.width, data.height);
        }
    });

})

function newImg(callback) {
    const obj = cropInstance.getValue();
    const image = new Image();
    image.src = url.value
    image.onload = () => {
        var canvas = document.createElement('canvas');
        canvas.width = obj.width;
        canvas.height = obj.height;
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(image, -obj.x, -obj.y);
        var canvas2;
        if (obj.width > option.value.width) {
            canvas2 = document.createElement('canvas');
            canvas2.width = option.value.width;
            canvas2.height = option.value.height;
            var ctx2 = canvas2.getContext("2d");
            ctx2.drawImage(canvas, 0, 0, canvas2.width, canvas2.height);
        }
        callback && callback(canvas2 ? canvas2 : canvas);
    }
}

function onSubmit() {
    newImg(function (canvas) {
        sindEmit(canvas);
    })
}

function onDownimg() {
    newImg(function (canvas) {
        onDownCanvas(canvas, '封面图.jpg');
    })
}

</script>
<template>

    <div class="cropp" style="width: 100%; height: 520px; overflow: auto;">
        <img id="croppr" :src="url" style="height: 500px;">
    </div>
    <el-button type="primary" @click="onSubmit">确定</el-button>
    <el-button type="primary" plain @click="onDownimg">下载</el-button>
</template>
<style scoped>
.cropp :deep(.croppr-container img) {
    max-width: none;
    height: 500px;
}
.cropp :deep(.croppr-container) {
    text-align: center;
}
</style>